package com.example.fw;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.PersonData;

public class PersonHelper extends HelperBase {

	public PersonHelper(ApplicationManager manager) {
		super(manager);
	}

	public void openAddPersonPage() {
		click(By.linkText("add new"));
	}

	public void submitPersonCreation() {
		click(By.name("submit"));
	}

	public void fillAddPersonForm(ApplicationManager applicationManager,
			PersonData person) {
		type(By.name("firstname"), person.firstName);
		type(By.name("lastname"), person.lastName);
		type(By.name("address"), person.address);
		type(By.name("home"), person.home);
		type(By.name("mobile"), person.mobile);
		type(By.name("work"), person.work);
		type(By.name("email"), person.email);
		type(By.name("email2"), person.secondEmail);
		selectByText(By.name("bday"), person.day);
		selectByText(By.name("bmonth"), person.month);
		type(By.name("byear"), person.year);
		// selectByText(By.name("new_group"), groupName);
		type(By.name("address2"), person.secondAddress);
		type(By.name("phone2"), person.secondHome);
	}

	public void initPersonModifications(int index) {
		click(By.cssSelector("tr[name=entry]:nth-child(" + (index + 1)
				+ ") a[href^='edit.php?id=']"));
	}

	public void updatePerson() {
		click(By.cssSelector("input[value=Update]"));
	}

	public void deletePerson() {
		click(By.cssSelector("input[value=Delete]"));
	}

	public List<PersonData> getPersons() {
		List<PersonData> persons = new ArrayList<PersonData>();
		List<WebElement> rows = driver.findElements(By
				.xpath("//tr[@name='entry']"));
		for (WebElement row : rows) {
			PersonData person = new PersonData();
			List<WebElement> personAttributes = row.findElements(By
					.cssSelector("td"));
			person.firstName = personAttributes.get(2).getText();
			person.lastName = personAttributes.get(1).getText();
			person.email = personAttributes.get(3).getText();
			person.mobile = personAttributes.get(4).getText();
			persons.add(person);

		}
		return persons;
	}

	public void fillSelectsRandomly(PersonData person) {
		person.day = getRandomBDay();
		person.month = getRandomBMonth();
		person.groupName = getRandomGroup();
	}
	
	public String getRandomBDay() {
		WebElement bDaySelect = driver.findElement(By.cssSelector("select[name='bday']"));
		WebElement randomBDay = getRandomOption(bDaySelect);
		return randomBDay.getText();
	}
	
	public String getRandomBMonth() {
		WebElement bMonthSelect = driver.findElement(By.cssSelector("select[name='bmonth']"));
		WebElement randomBMonth = getRandomOption(bMonthSelect);
		return randomBMonth.getText();
	}
	
	public String getRandomGroup() {
		WebElement groupSelect = driver.findElement(By.cssSelector("select[name='new_group']"));
		WebElement randomGroup = getRandomOption(groupSelect);
		return randomGroup.getText();
	}
}
